import re

# 想匹配或者搜索特定模式的文本
def demo_1():
    text = 'yeah, but no, but yeah, but no, but yeah'
    # find方法寻找第一个符合的字符串的下标
    num = text.find('no')
    print(num)

# 从字符串内匹配固定的部分字符串
def demo_2():
    datepat = re.compile(r'\d+/\d+/\d+')
    text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
    match_result = datepat.findall(text)
    print(match_result)

# 分别将每个组的内容提取出来,比如提取日期
def demo_3():
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
    m = datepat.match('11/27/2012')
    print(m.group(0))
    print(m.group(1))
    print(m.group(2))
    print(m.group(3))
    print(m.groups())
    month, day, year = m.groups()
    print('{}, {}, {}'.format(month, day, year))

def demo_4():
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
    text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
    match_result = datepat.findall(text)
    print(match_result)
    for month, day, year in datepat.findall(text):
        print('{}-{}-{}'.format(year, month, day))

# 如果打算做大量的匹配和搜索操作，最好先编译正则
def demo_5():
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)$')
    print(datepat.match('11/27/2012asda'))
    print(datepat.match('11/27/2012'))
    text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
    match_result = re.findall(r'(\d+)/(\d+)/(\d+)', text)
    print(match_result)

if __name__ == '__main__':
    # demo_1()
    # demo_2()
    # demo_3()
    # demo_4()
    demo_5()